package com.primb.bench.project.search.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.primb.baselibs.override.SpaceItemDecoration;
import com.primb.baselibs.util.FormatUtils;
import com.primb.baselibs.util.NetworkUtils;
import com.primb.baselibs.util.StringUtils;
import com.primb.baselibs.view.AutoToolbar;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.project.search.contract.SearchListContract;
import com.primb.bench.project.search.entity.PriceListEntity;
import com.primb.bench.project.search.entity.RequestPriceEntity;
import com.primb.bench.project.search.presenter.SearchListPresenterImpl;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.lankton.flowlayout.FlowLayout;

/**
 * Created by Chen on 2017/5/25.
 * 功能描述：
 */

public class SearchPriceActivity extends SwipeBaseActivity implements SearchListContract.View<PriceListEntity.DataBean> {
    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.recycler_add_info)
    RecyclerView recyclerAddInfo;
    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.swipe_content)
    SwipeRefreshLayout swipeContent;
    @BindView(R.id.layout_search_condition)
    FlowLayout layoutSearchCondition;
    @BindView(R.id.layout_condition_content)
    RelativeLayout layoutConditionContent;
    private ArrayList<PriceListEntity.DataBean> dataList;
    private SearchListPresenterImpl mPresenter;
    private BaseQuickAdapter<PriceListEntity.DataBean, BaseViewHolder> quickAdapter;

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_search_price;
    }

    @Override
    protected void onBaseBindView() {
        titleBar.setText("定价信息");
        ivTop.setVisibility(View.VISIBLE);
        ivTop.setImageResource(R.mipmap.ic_search_white_18dp);
        toolBar.setNavigationOnClickListener(v -> SearchPriceActivity.this.finish());
        swipeContent.setColorSchemeColors(ContextCompat.getColor(this, android.R.color.holo_blue_bright), ContextCompat.getColor(this, android.R.color.holo_green_light),
                ContextCompat.getColor(this, android.R.color.holo_orange_light), ContextCompat.getColor(this, android.R.color.holo_red_light));
        swipeContent.setRefreshing(true);
        configListView();
    }

    @Override
    protected void onLoadData() {
        mPresenter = new SearchListPresenterImpl(this, this, SearchListContract.KEY_PRICE);
        mPresenter.start();
    }

    @Override
    public void showLoading() {
        if (swipeContent != null) {
            swipeContent.setRefreshing(true);
        }
    }

    @Override
    public void hideLoading() {
        if (swipeContent != null && swipeContent.isRefreshing()) {
            swipeContent.setRefreshing(false);
        }
    }

    @Override
    public void showError(String error) {
        showToast(error);
    }

    @Override
    public void configListView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerAddInfo.setLayoutManager(layoutManager);
        recyclerAddInfo.setHasFixedSize(true);
        dataList = new ArrayList<>();

        quickAdapter = new BaseQuickAdapter<PriceListEntity.DataBean, BaseViewHolder>(R.layout.item_search_price, dataList) {

            @Override
            protected void convert(BaseViewHolder helper, PriceListEntity.DataBean item) {
                helper.setText(R.id.tv_item_search_serial_number, item.getPriceId());
                helper.setText(R.id.tv_item_search_client_name, item.getCustName());
                helper.setText(R.id.tv_item_search_loan_type, item.getLnPrdName());
                helper.setText(R.id.tv_item_search_part_name, item.getOrgDesc());
                helper.setText(R.id.tv_item_search_apply_type, item.getPriceType().equals("02") ? "贷款定价申请" : "贷款定价试算");
                helper.setText(R.id.tv_item_search_stock_date, item.getPriceDate());
                helper.setText(R.id.tv_item_search_part_number, item.getOrgId());
                helper.setText(R.id.tv_item_search_client_number, item.getCustId());
                helper.setText(R.id.tv_item_search_manager_number, item.getCustMngId());
                helper.setText(R.id.tv_item_search_client_manager, item.getCustMngName());
                helper.setText(R.id.tv_item_search_loan_money, FormatUtils.format2Int(item.getLnAmt()));
                helper.setText(R.id.tv_item_search_direct_rate, StringUtils.double2String(Double.valueOf(item.getCustGdIr()) * 100, 4));
            }
        };
        quickAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(SearchPriceActivity.this, SearchDetailActivity.class);
            intent.putExtra("priceId", dataList.get(position).getPriceId());
            intent.putExtra("priceType", dataList.get(position).getPriceType());
            intent.putExtra("isReapply", false);
            startActivity(intent);
        });
        quickAdapter.setOnLoadMoreListener(() -> {
            if (!NetworkUtils.isNetworkConnected(this)) {
                showError("无网络连接，请连接网络后重试");
                quickAdapter.loadMoreFail();
                return;
            }
            mPresenter.loadMoreList();
        }, recyclerAddInfo);
        View layoutEmpty = getLayoutInflater().inflate(R.layout.empty_list_view, (ViewGroup) recyclerAddInfo.getParent(), false);
        quickAdapter.setEmptyView(layoutEmpty);
        quickAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        quickAdapter.setNotDoAnimationCount(0);
        quickAdapter.isFirstOnly(true);
        recyclerAddInfo.setAdapter(quickAdapter);
        swipeContent.setOnRefreshListener(() -> {
            if (!NetworkUtils.isNetworkConnected(this)) {
                showError("无网络连接，请连接网络后重试");
                swipeContent.setRefreshing(false);
                return;
            }
            mPresenter.start();
        });
    }

    @Override
    public void setDataToList(List<PriceListEntity.DataBean> entity) {
        swipeContent.setRefreshing(false);
        dataList.clear();
        dataList.addAll(entity);
        quickAdapter.setNewData(dataList);
    }

    @Override
    public void loadMoreList(List<PriceListEntity.DataBean> entity) {
        if (entity.size() > 0) {
            quickAdapter.addData(entity);
            quickAdapter.notifyDataSetChanged();
            quickAdapter.loadMoreComplete();
        } else {
            quickAdapter.loadMoreEnd();
        }
    }

    @Override
    public void loadMoreField() {
        quickAdapter.loadMoreFail();
    }

    @Override
    public void clearListData() {
        dataList.clear();
        quickAdapter.getData().clear();
        quickAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstant.SEARCH_PRICE_REQUEST && resultCode == AppConstant.SEARCH_PRICE_RESULT) {
            RequestPriceEntity info = data.getParcelableExtra("info");
            mPresenter.showSearchCondition(info, layoutSearchCondition);
            if (layoutSearchCondition.getChildCount() > 0) {
                layoutSearchCondition.setVisibility(View.VISIBLE);
                layoutConditionContent.setVisibility(View.VISIBLE);
            } else {
                layoutSearchCondition.setVisibility(View.GONE);
                layoutConditionContent.setVisibility(View.GONE);
            }
            mPresenter.getDataList(info);
        }
    }

    @OnClick({R.id.iv_top, R.id.iv_delete_condition})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top:
                Intent intent = new Intent(this, PriceConditionActivity.class);
                intent.putExtra("info", mPresenter.getRequestPriceEntity());
                startActivityForResult(intent, AppConstant.SEARCH_PRICE_REQUEST);
                break;
            case R.id.iv_delete_condition:
                layoutSearchCondition.removeAllViews();
                layoutConditionContent.setVisibility(View.GONE);
                RequestPriceEntity requestPriceEntity = new RequestPriceEntity();
                requestPriceEntity.reSet();
                mPresenter.setEntity(requestPriceEntity);
                mPresenter.start();
                break;
        }
    }
}
